package initialize

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"net/http"
	"time"
	myjwt "zhejianglab/gin-apiserver/pkg/jwt"
	"zhejianglab/gin-apiserver/pkg/util"
	"zhejianglab/gin-apiserver/routers"

	"github.com/gin-gonic/gin"
)

// InitRouter init the routers
func InitRouter() *gin.Engine {

	Router := gin.Default()
	APIGroup := Router.Group("")
	//获取token路由
	myjwt.SetupGoGuardian()
	Router.POST("/token", GetAuth)

	//显示Map 路由
	//加载html模板
	//Router.LoadHTMLGlob("templates/online.html")
	//Router.LoadHTMLGlob("templates/index.html")
	//html模板调用的js
	//Router.Static("/js", "js")
	//Router.GET("/home", home)

	//显示Prometheus路由

	Router.GET("/metrics", gin.WrapH(promhttp.Handler()))

	// 方便统一添加路由组前缀 可以实现多服务器上线使用
	// 注册用户路由
	routers.InitUserRouter(APIGroup)
	routers.InitAlgoRouter(APIGroup)
	routers.InitJobRouter(APIGroup)
	routers.InitDatasetRouter(APIGroup)
	routers.InitDownloadRouter(APIGroup)
	routers.InitClueRouter(APIGroup)
	routers.InitFileRouter(APIGroup)
	routers.InitAlarmRouter(APIGroup)
	routers.InitConfigRouter(APIGroup)
	routers.InitVideoRouter(APIGroup)
	return Router
}

func home(c *gin.Context) {
	c.HTML(http.StatusOK, "online.html", nil)
	//c.HTML(http.StatusOK, "index.html", nil)
}

func createToken(c *gin.Context) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"iss": "auth-app",
		"sub": "admin",
		"aud": "any",
		"exp": time.Now().Add(time.Minute * 5).Unix(),
	})
	jwtToken, _ := token.SignedString([]byte("secret"))
	c.Writer.Write([]byte(jwtToken))
}

type Claims struct {
	Username string `json:"username"`
	Password string `json:"password"`
	jwt.StandardClaims
}

func GetAuth(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	nowTime := time.Now()
	expireTime := nowTime.Add(3 * time.Hour)

	//todo 增加对用户名密码校验 和数据库查询判断是否密码正确

	claims := Claims{
		Username: util.EncodeMD5(username),
		Password: util.EncodeMD5(password),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "gin-blog",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	jwtToken, _ := token.SignedString([]byte("secret"))
	c.Writer.Write([]byte(jwtToken))
}
